import React, { FC, useEffect, useState } from "react";
import { Select } from "antd";
import Https from "@/utils/Https";
import debounce from "lodash/debounce";
interface propType {
  onSuccess: (e) => void; //上传成功的回调事件
  url: string;
  methods?: string;
  conditon: string;
  value?: string;
  params?: Object;
  placeholder?: string;
  style?: Object;
  showSearch?: boolean;
}
const SelectSearch: FC<propType> = (props) => {
  const {
    onSuccess,
    methods,
    url,
    conditon,
    value,
    params,
    placeholder,
    style,
    showSearch = true,
  } = props;
  const [data, setData] = useState([]);
  const getList = async (val) => {
    let obj = {
      current: 1,
      pageSize: 10,
      ...params,
    };
    obj[conditon] = val;
    let method = methods ? methods : "post";
    let res: any = await Https[method](url, obj);
    if (res && res.records && res.records.length > 0) {
      setData(res.records);
    } else {
      setData([]);
    }
  };
  const handleSearch = debounce(function (value) {
    getList(value);
  }, 1000);
  useEffect(() => {
    getList("");
  }, []);
  return (
    <Select
      onChange={(e) => {
        let paramsObj = data.filter(function (o) {
          return o.id == e;
        })[0];
        onSuccess(paramsObj);
      }}
      value={value}
      style={style}
      onSearch={handleSearch}
      showSearch={showSearch}
      filterOption={false}
      getPopupContainer={(triggerNode) => triggerNode.parentElement}
      placeholder={placeholder ? placeholder : "请选择"}
    >
      {data &&
        data.map((e: { id: string; name: string }) => (
          <Select.Option key={e.id} value={e.id}>
            {e[conditon]}
          </Select.Option>
        ))}
    </Select>
  );
};

export default SelectSearch;
